'''
Created on Apr 5, 2009

@author: Administrator
'''
import os
from django.db import models
from django.contrib.auth.models import User
from settings import BASE_UPLOAD_DIR as upload_dir
from com.ericyang.common.web.middleware import threadlocals

CATEGORY_TOP_LEVEL = 3

def correct_level(_level=1):
    level = int(_level)
    if level > CATEGORY_TOP_LEVEL or level < 1:
        return 1
    else:
        return level
    
class Category(models.Model):
    name = models.CharField(max_length=20, null=False)
    url = models.CharField(max_length=255, null=True)
    super_category = models.ForeignKey("self", null=True)
    level = models.IntegerField(default=1)

    def get_level(self):
        level = 1;
        if self.super_category:
            level = self.super_category.get_level() + level;
        return level;
    
    def get_category_chain(self):
        chain = self.name
        if self.super_category:
            chain = self.super_category.get_category_chain() + ' - ' + chain;
        return chain;
        
    
class Product(models.Model):
    name = models.CharField(max_length=200, null=False)
    introducation = models.TextField(max_length=2000, null=False)
    marketPrice = models.DecimalField("market price", max_digits=12, decimal_places=2);
    imagePath = models.CharField(max_length=255)
    category = models.ForeignKey(Category, null=False)
    user = models.ForeignKey(User)
    create_time = models.DateTimeField("create time")
    
    def is_changable(self):
        return self.user.id == threadlocals.get_current_user().id
    
    def delete_image(self):
        img = upload_dir + self.imagePath
        try:
            os.remove(img)
        except WindowsError:
            print "No file named '%s'", img
    
    def delete(self):
        self.delete_image()
        super(Product, self).delete()
        
    def save(self):
        if self.user == None:
            self.user = threadlocals.get_current_user()
        super(Product, self).save()